package com.showsu.editor.utils.aliyun;

import com.aliyun.mts20140618.Client;
import com.aliyun.mts20140618.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;


/**
 * @Author: Johnplue
 * @Description: 阿里云MTS工具类
 * @Date: Created in 13:00 下午 2023/8/15
 * @Modified By:
 */
@Slf4j
@Component
public class MTSSubmitJobsUtil extends BaseAliyunUtil<Client> {

    @Value("${aliyun.mps.endpoint.mts}")
    private String endpoint;

    @Value("${aliyun.mps.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.mps.accessKeySecret}")
    private String accessKeySecret;

    @Override
    public void initClient(String accessKeyId, String accessKeySecret, String endpoint) {
        try {
            this.client= this.createClient(accessKeyId,accessKeySecret,endpoint);
        }catch (Exception e) {
            System.out.println("阿里云MTS工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }
    @PostConstruct
    public void init(){
        System.out.println("开始实例化 阿里云MTS工具类");
        this.initClient(accessKeyId,accessKeySecret,endpoint);
        System.out.println("结束实例化 阿里云MTS工具类");
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @param endpoint
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret,String endpoint) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Mts
        config.endpoint =endpoint;
        return new Client(config);
    }
    public String run( Client client,SubmitJobsRequest submitJobsRequest){
        String statusCode="";
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SubmitJobsResponse t=client.submitJobsWithOptions(submitJobsRequest, runtime);
            List<SubmitJobsResponseBody.SubmitJobsResponseBodyJobResultListJobResult> list=t.body.getJobResultList().getJobResult();
            statusCode=t.getStatusCode().toString();
            if("200".equals(statusCode)&&list!=null&&list.size()>0){
                QueryJobListRequest queryJobListRequest = new QueryJobListRequest()
                        .setJobIds(list.get(0).getJob().jobId);
                while (true){
                    QueryJobListResponse  queryJobListResponse=client.queryJobListWithOptions(queryJobListRequest, runtime);
                    String queryJobListStatusCode=queryJobListResponse.getStatusCode().toString();
                    if(! "200".equals(queryJobListStatusCode)){
                        statusCode=queryJobListStatusCode;
                        break;
                    }

                    if(queryJobListResponse.getBody().getNonExistJobIds()!=null
                            &&queryJobListResponse.getBody().getNonExistJobIds().getString()!=null
                            &&queryJobListResponse.getBody().getNonExistJobIds().getString().size()>0){
                        statusCode="404";
                        break;
                    }
                    List<QueryJobListResponseBody.QueryJobListResponseBodyJobListJob> queryList=queryJobListResponse.getBody().getJobList().getJob();
                    if(queryList==null||queryList.size()<=0){
                        statusCode="404";
                        break;
                    }
                    if(queryList.get(0).getPercent()>=100L){
                        statusCode="200";
                        break;
                    }
                    log.info("等待视频转音频"+list.get(0).getJob().jobId);
                    Thread.sleep(1000);
                }

            }else{
                statusCode="400";
            }


        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            statusCode=error.code;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            statusCode=error.code;
        }
        return statusCode;
    }

    public String start(String accessKeyId,String accessKeySecret,String endpoint,String bucket,String location,String object,String outputBucket,String outputObject,String templateId,String userData,String pipelineId) {
        try {
            Client newClient= this.createClient(accessKeyId,accessKeySecret,endpoint);
            return start(newClient,bucket,location,object,outputBucket,outputObject,templateId,userData,pipelineId);
        }catch (Exception e) {
            log.error("start方法 阿里云MTS工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public String start(Client thisClient,String bucket,String location,String object,String outputBucket,String outputObject,String templateId,String userData,String pipelineId) {
        SubmitJobsRequest submitJobsRequest = new SubmitJobsRequest()
                .setInput("{\"Bucket\":\""+bucket+"\",\"Location\":\""+location+"\",\"Object\":\""+object+"\"}")
                .setOutputs("[{\"OutputObject\":\""+outputObject+"\",\"TemplateId\":\""+templateId+"\",\"UserData\":\""+userData+"\"}]")
                .setOutputBucket(outputBucket)
                .setPipelineId(pipelineId);

        return run(thisClient,submitJobsRequest);
    }

    public String start(String bucket,String location,String object,String outputBucket,String outputObject,String templateId,String userData,String pipelineId) {
        if(this.client==null){
            return start(accessKeyId,accessKeySecret,endpoint,bucket,location,object,outputBucket,outputObject,templateId,userData,pipelineId);
        }
        return start(this.client,bucket,location,object,outputBucket,outputObject,templateId,userData,pipelineId);
    }

    public String start(String object,String outputObject,String userData){
        String statusCode="";
        statusCode=start("showsu","oss-cn-hangzhou",object,"showsu",outputObject,"81bf5bf8ca514c1d8632b77a0127ea69",userData,"fcac3a8f7ffc4318a491a6a38f851626");
        return statusCode;
    }



}
